import { logout, reqLogin, reqLogout, reqUserInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter, asyncRouter, constantRoutes, anyRouter } from "@/router";
import cloneDeep from "lodash/cloneDeep";
import router from "@/router/index";
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    buttons: [],
    menuRoutes: [],
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SETTOKEN: (state, token) => {
    state.token = token;
  },
  SETNAME: (state, name) => {
    state.name = name;
  },
  SETAVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SETROUTER: (state, payloud) => {
    state.buttons = payloud.buttons;
  },
  SETROUTE: (state, route) => {
    state.menuRoutes = route;
  },
};

function filterAsyncRoute(asyncR, routeArr) {
  return asyncR.filter((route) => {
    //先过滤一级路由
    if (routeArr.includes(route.name)) {
      //递归过滤子集路由
      if (route.children && route.children.length > 0) {
        route.children = filterAsyncRoute(route.children, routeArr);
      }
      return true;
    }
  });
}
const actions = {
  // user login
  async login({ commit }, userInfo) {
    try {
      const result = await reqLogin(userInfo);
      if (result.code == 20000) {
        setToken(result.data.token);
        commit("SETTOKEN", result.data.token);
      }
    } catch (error) {
      console.log(error);
    }
  },

  /*  */
  async getInfo({ commit, state }) {
    const result = await reqUserInfo();
    // console.log(result.data);

    const useRoutes = filterAsyncRoute(
      cloneDeep(asyncRouter),
      result.data.routes
    );
    resetRouter();
    //动态添加路由
    router.addRoutes([...constantRoutes, ...useRoutes, ...anyRouter]);
    // console.log(router);

    commit("SETNAME", result.data.name);
    commit("SETAVATAR", result.data.avatar);
    commit("SETROUTE", [...constantRoutes, ...useRoutes, ...anyRouter]);
    commit("SETROUTER", result.data);
    // console.log(result.data.routes);
  },

  // user logout
  async logout({ commit, state }) {
    const result = await reqLogout();
    resetRouter();
    router.go("/");
    removeToken(); //删除token
    commit("RESET_STATE");
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
